package com.plr.booker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.base.Joiner;

public class BookCommons {
	
	
	static OutputStream createFile(String... params) throws Exception {
		Date date = new Date() ;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
		
		String ps = Joiner.on("").join(params);
		
		File file = new File( ps + " " + dateFormat.format(date) + ".xml");
		
		file.getParentFile().mkdirs();
		
		OutputStream out = new FileOutputStream(file);
	
		return out;
	}
	
	static private Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
	
	static public String  replace(String text, Map<String,String> replacements) {
		
		
		Matcher matcher = pattern.matcher(text);
	
		StringBuilder builder = new StringBuilder();
		int i = 0;
		while (matcher.find()) {
		    String replacement = replacements.get(matcher.group(1));
		    builder.append(text.substring(i, matcher.start()));
		    if (replacement == null)
		        builder.append(matcher.group(0));
		    else
		        builder.append(replacement);
		    i = matcher.end();
		}
		
		builder.append(text.substring(i, text.length()));
		
		return builder.toString();
	} 
}
